﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common {
    class DisposeHelper {
        public static void DisposeAllDisposableMembers(object obj) {
            Type t = obj.GetType();
            var fields = t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            //foreach (var field in fields) {
            //    if (isIDisposeable(field)){
            //        disposeField(obj, field);
            //    }
            //}
            List<FieldInfo> fieldList = new List<FieldInfo>(fields);


            fields.Foreach((FieldInfo field) =>
            {
                if (isIDisposeable(field)) {
                    disposeField(obj, field);
                }
            });
        }

        private static void disposeField(object obj, FieldInfo field) {
            var fieldInstance = field.GetValue(obj);
            IDisposable disposableField = (IDisposable)fieldInstance;
            disposableField.Dispose();
        }

        private static bool isIDisposeable(FieldInfo field) {
            var fieldType = field.FieldType;
            if (fieldType.GetInterface("System.IDisposable") == null) {
                return false;
            }
            else {
                return true;
            }
        }
    }
}
